package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.http.api.AddAddressApi;
import xhwl.hmo.mall.http.api.UpdateAddressApi;
import xhwl.hmo.mall.http.bean.resp.AddressInfoResp;
import xhwl.hmo.mall.http.bean.resp.AddressListResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.utils.NumberJudgeUtils;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 添加新地址
 */
public class AddNewAddressActivity extends BaseActivity implements View.OnClickListener {
    public static final String EXTRA_DATA = "data";
    private EditText receiver;
    private EditText phone;
    private TextView address;
    private EditText address_detail;
    private Button info_assure;
    private RelativeLayout rl_diqu;
//    private OptionsPickerView pvOptions;//地址选择器
//    private ArrayList<String> Provincestr = new ArrayList<>();//省
//    private ArrayList<ArrayList<String>> Citystr = new ArrayList<>();//市
//    private ArrayList<ArrayList<ArrayList<String>>> Areastr = new ArrayList<>();//区
//
//    private ArrayList<Province> provinceList = new ArrayList<>();//省
//    private ArrayList<ArrayList<City>> cityList = new ArrayList<>();//市
//    private ArrayList<ArrayList<ArrayList<Area>>> areaList = new ArrayList<>();//区

    AddressListResp.Address data;
    AddressInfoResp.ProvinceInfo provinceInfo;
    AddressInfoResp.CityInfo cityInfo;
    AddressInfoResp.DistrictInfo areaInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data= (AddressListResp.Address) getIntent().getSerializableExtra(EXTRA_DATA);
        setContentView(R.layout.activity_add_new_address);
    }

    @Override
    public void initViews() {
        initTitleViews();
        receiver = (EditText) findViewById(R.id.receiver);
        phone = (EditText) findViewById(R.id.phone);
        address = (TextView) findViewById(R.id.address);
        address_detail = (EditText) findViewById(R.id.address_detail);
        info_assure = (Button) findViewById(R.id.info_assure);
        rl_diqu= (RelativeLayout) findViewById(R.id.rl_diqu);
//        getAddressData();
//        initPickerView();
        //如果是编辑地址
        if(data!=null){
            initData();
        }
    }

    private void initData() {
        provinceInfo=new AddressInfoResp.ProvinceInfo(data.PROVINCE_ID,data.PROVINCE_NAME);
        cityInfo=new AddressInfoResp.CityInfo(data.CITY_ID,data.CITY_NAME);
        areaInfo=new AddressInfoResp.DistrictInfo(data.DISTRICT_ID,data.DISTRICT_NAME);
        receiver.setText(data.SH_NAME);
        receiver.setSelection(data.SH_NAME.length());
        phone.setText(data.SH_MOBILE);
        address.setText(data.PROVINCE_NAME+data.CITY_NAME+data.DISTRICT_NAME);
        address_detail.setText(data.SH_ADDRESS);
    }

//    private void initPickerView() {
//        //选项选择器
//        pvOptions = new OptionsPickerView(this);
//        //设置三级联动效果
//        pvOptions.setPicker(Provincestr, Citystr, Areastr, true);
//        //设置选择的三级单位
////        pvOptions.setLabels("省", "市", "区");
//        pvOptions.setTitle("选择城市");
//        //设置是否循环滚动
//        pvOptions.setCyclic(false, false, false);
//        //设置默认选中的三级项目
//        //监听确定选择按钮
//        pvOptions.setSelectOptions(0, 0, 0);
//        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3) {
//                //返回的分别是三个级别的选中位置
//                String tx = Provincestr.get(options1)
//                        + Citystr.get(options1).get(option2)
//                        + Areastr.get(options1).get(option2).get(options3);
//                address.setText(tx);
//            }
//        });
//    }


    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        if(data!=null){
            titleTextView.setText("修改地址");
        }
        else
        {
            titleTextView.setText("添加新地址");
        }
    }

    @Override
    public void initListener() {
        info_assure.setOnClickListener(this);
        rl_diqu.setOnClickListener(this);

    }

    @Override
    public void loadData() {

    }

    private boolean vilidInput(){
        String msg="";
        String name = receiver.getText().toString().trim();
        String phoneStr = phone.getText().toString().trim();
        String addressStr=address.getText().toString().trim();
        String detail = address_detail.getText().toString().trim();
        if (StringUtil.isEmpty(name)) {
            msg="请输入收货人的姓名";
        }
        else if (StringUtil.isEmpty(phoneStr)) {
            msg="请输入收货人的联系电话";
        }
        else if (phoneStr.length() != 11) {
            msg = "请输入11位号码";
        }
        else if (! NumberJudgeUtils.isMobileNO(phoneStr)) {
            msg = "手机号格式有误，请输入正确的手机号";
        }
        else if (StringUtil.isEmpty(addressStr)) {
            msg = "请选择所在地区";
        }
        else if (StringUtil.isEmpty(detail)) {
            msg ="请填写您的详细地址";
        }
        if(!StringUtil.isEmpty(msg)){
            ToastUtil.showToast(mContext,msg);
            return false;
        }
        return true;
    }
    private void update(){
        String memberMobile= SpUtil.getString(SpUtil.MEMBER_MOBILE,"");

        UpdateAddressApi api=new UpdateAddressApi(data.RECORD_ID,memberMobile,receiver.getText().toString().trim(), phone.getText().toString().trim(),
                provinceInfo.PROVINCE_ID,cityInfo.CITY_ID,areaInfo.DISTRICT_ID,address_detail.getText().toString().trim());
        HttpManager.getInstance().dealHttp(this,api, new OnNextListener<HttpResp>(){
            @Override
            public void onNext(HttpResp httpResp) {
                if(httpResp.isOk()){
                    ToastUtil.showToast(mContext,"修改成功");
                    setResult(RESULT_OK);
                    finish();
                }
                else
                {
                    ToastUtil.showToast(mContext,httpResp.message);
                }
            }
        });

    }
    private void submit() {
        String memberMobile= SpUtil.getString(SpUtil.MEMBER_MOBILE,"");

        AddAddressApi api=new AddAddressApi(memberMobile,receiver.getText().toString().trim(), phone.getText().toString().trim(),
                provinceInfo.PROVINCE_ID,cityInfo.CITY_ID,areaInfo.DISTRICT_ID,address_detail.getText().toString().trim());
        HttpManager.getInstance().dealHttp(this,api, new OnNextListener<HttpResp>(){
            @Override
            public void onNext(HttpResp httpResp) {
                if(httpResp.isOk()){
                    ToastUtil.showToast(mContext,"添加成功");
                    setResult(RESULT_OK);
                    finish();
                }
                else
                {
                    ToastUtil.showToast(mContext,httpResp.message);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_diqu://地址选择
//                pvOptions.show();
                Intent intent=new Intent(mContext,SelectAddrActivity.class);
                startActivityForResult(intent,0);
                break;
            case R.id.info_assure://信息提交
                if(vilidInput()){
                    if(data!=null){
                        update();
                    }else
                    {
                        submit();
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0&&resultCode==RESULT_OK){
            if(data!=null){
                provinceInfo= (AddressInfoResp.ProvinceInfo) data.getSerializableExtra("province");
                cityInfo= (AddressInfoResp.CityInfo) data.getSerializableExtra("city");
                areaInfo= (AddressInfoResp.DistrictInfo) data.getSerializableExtra("area");
                address.setText(provinceInfo.PROVINCE_NAME+cityInfo.CITY_NAME+areaInfo.DISTRICT_NAME);
            }
        }
    }
    //    private void getAddressInfo() {
//        String memberMobile= SpUtil.getString(SpUtil.MEMBER_MOBILE,"");
//        if(StringUtil.isEmpty(memberMobile))
//        {
//            return;
//        }
//        BaseApi api=new AddressInfoApi1(memberMobile);
//        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<ArrayList<AddressInfoResp1>>>() {
//            @Override
//            public void onNext(HttpResp<ArrayList<AddressInfoResp1>> resp) {
//                if(resp!=null){
//                    ArrayList<AddressInfoResp1> list=resp.data;
//                    for(AddressInfoResp1 bean:list){
//                        Province province=new Province(bean.PROVINCE_ID,bean.PROVINCE_NAME);
//                        City city=new City(bean.CITY_ID,bean.CITY_NAME);
//                        Area area=new Area(bean.DISTRICT_ID,bean.DISTRICT_NAME);
//                        if(!provinceList.contains(province)){
//                            provinceList.add(province);
//                        }
//                        province=provinceList.get(provinceList.indexOf(province));
//
//                        ArrayList<City> citys=province.getCityList();
//                        if(!citys.contains(city)){
//                            citys.add(city);
//                        }
//                        city=citys.get(citys.indexOf(city));
//
//                        ArrayList<Area> areas=city.getArealist();
//                        if(!areas.contains(area)){
//                            areas.add(area);
//                        }
//                        area=areas.get(citys.indexOf(area));
//
//                    }
//                }
//            }
//        });
//    }
//    private void getAddressData() {
//        // 获取数据库
//        SQLiteDatabase db = DBManager.getdb(getApplication());
//        //省
//        Cursor cursor = db.query("province", null, null, null, null, null,
//                null);
//        while (cursor.moveToNext()) {
//            int pro_id = cursor.getInt(0);
//            String pro_code = cursor.getString(1);
//            String pro_name = cursor.getString(2);
//            String pro_name2 = cursor.getString(3);
//            ProvinceBean provinceBean = new ProvinceBean(pro_id, pro_code, pro_name, pro_name2);
////            options1Items.add(provinceBean);//添加一级目录
//            Provincestr.add(cursor.getString(2));
//            //查询二级目录，市区
//            Cursor cursor1 = db.query("city", null, "province_id=?", new String[]{pro_id + ""}, null, null,
//                    null);
//            ArrayList<CityBean> cityBeanList = new ArrayList<>();
//            ArrayList<String> cityStr = new ArrayList<>();
//            //地区集合的集合（注意这里要的是当前省份下面，当前所有城市的地区集合我去）
//            ArrayList<ArrayList<AreaBean>> options3Items_03 = new ArrayList<>();
//            ArrayList<ArrayList<String>> options3Items_str = new ArrayList<>();
//            while (cursor1.moveToNext()) {
//                int cityid = cursor1.getInt(0);
//                int province_id = cursor1.getInt(1);
//                String code = cursor1.getString(2);
//                String name = cursor1.getString(3);
//                String provincecode = cursor1.getString(4);
//                CityBean cityBean = new CityBean(cityid, province_id, code, name, provincecode);
//                //添加二级目录
//                cityBeanList.add(cityBean);
//                cityStr.add(cursor1.getString(3));
//                //查询三级目录
//                Cursor cursor2 = db.query("area", null, "city_id=?", new String[]{cityid + ""}, null, null,
//                        null);
//                ArrayList<AreaBean> areaBeanList = new ArrayList<>();
//                ArrayList<String> areaBeanstr = new ArrayList<>();
//                while (cursor2.moveToNext()) {
//                    int areaid = cursor2.getInt(0);
//                    int city_id = cursor2.getInt(1);
////                    String code0=cursor2.getString(2);
//                    String areaname = cursor2.getString(3);
//                    String citycode = cursor2.getString(4);
//                    AreaBean areaBean = new AreaBean(areaid, city_id, areaname, citycode);
//                    areaBeanList.add(areaBean);
//                    areaBeanstr.add(cursor2.getString(3));
//                }
//                options3Items_str.add(areaBeanstr);//本次查询的存储内容
//                options3Items_03.add(areaBeanList);
//            }
////            options2Items.add(cityBeanList);//增加二级目录数据
//            Citystr.add(cityStr);
////            options3Items.add(options3Items_03);//添加三级目录
//            Areastr.add(options3Items_str);
//        }
//    }
}
